<?php 
class kdtrace_fedex extends Controller {
	
	function track( $tracknum , $lang = "en"){
		if($lang=="ch"){$langset = "zh_CN";} else {$langset = "en_US";};
		$getdata = array(
			"action"	=>	"trackpackages",
			"locale"	=>	$langset,
			"version"	=>	"1",
			"format"	=>	"json",
			"data"		=>	'{"TrackPackagesRequest":{"appType":"WTRK","uniqueKey":"","processingParameters":{},"trackingInfoList":[{"trackNumberInfo":{"trackingNumber":"'.$tracknum.'","trackingQualifier":"","trackingCarrier":""}}]}}',
			"_"			=>	time()
		);
		$url = "https://www.fedex.com/trackingCal/track?" . http_build_query($getdata, '', '&');
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Referer: https://www.fedex.com/fedextrack/WTRK/index.html',
			'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36' 
		));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);

		$result = curl_exec($ch);
        curl_close($ch);
		$result = json_decode($result);
		$rtndata = array('tracknum'=>$tracknum,'header'=>array(),'err'=>array(),'eventList'=>array());
		if( $result->TrackPackagesResponse->successful != "1"){
			$rtndata['err']['errcode'] = '1';
		}else{
			$rtndata['err']['errcode'] = '0';	
			$package = $result->TrackPackagesResponse->packageList[0];
	
			$rtndata['header']['shipFrom']			= $package->shipperCity;
			$rtndata['header']['shipTo']			= $package->recipientCity;
			$rtndata['header']['keyStatus']			= $package->keyStatus;
			$rtndata['header']['DetailStatus']		= $package->statusWithDetails;
			$rtndata['header']['keyStatusCD']		= $package->keyStatusCD;
			$rtndata['header']['SignedBy']			= $package->receivedByNm;
			
			$package->keyStatusCD=="DL" ? $rtndata['header']['isDelivered']=true : $rtndata['header']['isDelivered']=false;
						
			$i = 0;
			foreach( $package->scanEventList as $tlist){
				$tt =  strtotime($tlist->date . " " . $tlist->time);
				$rtndata['eventList'][$i] = array(
					"date"			=> date('Y-m-d',$tt),
					"time"			=> date('h:i:s',$tt),
					"utime"			=> $tt,
					"status"		=> $tlist->status,
					"location"		=> $tlist->scanLocation
				);
				$i++;
			}
		}
		$rtndata['eventList'] = array_reverse( $rtndata['eventList'] );
		return $rtndata;
	}
	
}

?>